package com.admin.interfaces.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
public class IndexController {

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping(value = "/auth/{appId}/{id}/{url}", method = RequestMethod.GET)
    public void auth(HttpServletRequest request, HttpServletResponse response,@PathVariable("appId") String appId, @PathVariable("id") String id, @PathVariable("url") String url) {
        String redirectUri = "http://"+url+"/authReturn";
        try {
            redirectUri= URLEncoder.encode(redirectUri,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String weixinUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        weixinUrl = weixinUrl.replace("APPID",appId).replace("STATE",id).replace("REDIRECT_URI",redirectUri);
        try {
            response.sendRedirect(weixinUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //RemoteDataUtil.getWeixin(weixinUrl);
    }

    //

    /**
     * http://127.0.0.1:8080/authReturn?response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect#wechat_redirect
     * @param request
     * @param response
     */
    @RequestMapping(value = "/authReturn", method = RequestMethod.GET)
    public void authReturn(HttpServletRequest request, HttpServletResponse response) {

        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String responseUrl = "http://cj.dwucity.com/Mobile/WeChat/UserInfo?code=aaaa&state=bbbbb";
        responseUrl = responseUrl.replace("aaaa",code).replace("bbbbb",state);
        try {
            response.sendRedirect(responseUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
